package com.zgc.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgc.entity.Menu;
import com.zgc.entity.TreeIndex;
import com.zgc.entity.TreeSelect;
import com.zgc.mapper.MenuMapper;
import com.zgc.service.MenuService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements
        MenuService {
    @Override
    public List<TreeIndex> buildTreeIndex(List<Menu> menuTree) {
        List<Menu> listmenus= buildTree(menuTree);
        return
                listmenus.stream().map(TreeIndex::new).collect(Collectors.toList());
    }
    @Override
    public List<TreeSelect> buildTreeSelect(List<Menu> menuTree) {
        List<Menu> listmenus= buildTree(menuTree);
        return
                listmenus.stream().map(TreeSelect::new).collect(Collectors.toList());
    }
    @Override
    public List<Menu> buildTree(List<Menu> menuTree) {
        List<Menu> returnlist=new ArrayList<>();
        List<Long> templist=new ArrayList<>();
        for (Menu menu:menuTree) {
            templist.add(menu.getId());
        }
        for (Iterator<Menu> iterator= menuTree.iterator();iterator.hasNext() ;)
        {
            Menu menu=iterator.next();
//如果是顶级节点，遍历下面所有子结点
            if(!templist.contains(menu.getParentId())){
                recursionFn(menuTree,menu);
                returnlist.add(menu);
            }
        }
        if(returnlist.isEmpty()){
            returnlist=menuTree;
        }
        return returnlist;
    }
    //获取此节点的子节点列表
    private void recursionFn (List<Menu> list,Menu t){
        List<Menu> childList = getchildList(list, t);
        t.setChildren(childList);
        for (Menu tchild : childList){
            if ( hasChild(list,tchild)){
                Iterator<Menu> it = childList.iterator();
                while (it.hasNext())
                {
                    Menu n = (Menu) it.next();//递归
                    recursionFn(list,n);
                }
            }
        }
    }
    /**
     * 获取子节点列表v
     * */
    private List<Menu> getchildList(List<Menu> list,Menu t){
        List<Menu> tlist=new ArrayList<>();
        Iterator<Menu> it= list.iterator();
        while(it.hasNext()){
            Menu n=it.next();
            if(null !=n.getParentId() && n.getParentId().intValue()
                    ==t.getId().intValue()){
                tlist.add(n);
            }
        }
        return tlist;
    }
    //查看是否有子节点
    private boolean hasChild(List<Menu> list,Menu t) {
        return getchildList(list,t).size()>0 ? true:false;
    }
}
